import os
import json

# 获取json文件名
def Obtain_json_name(txt_path):
    file_name_list = os.listdir(txt_path)
    json_name_list = []
    for each in file_name_list :
        each_list = each.split(".",2)
        if each_list[1] == "txt" :
            json_name_list.append(each_list[0]) 
    # print(json_name_list)
    return json_name_list

# 获取标准格式的json文件
def standard_json_content(json_path ):
    os.chdir(json_path)
    json_data_list = []
    for each in os.listdir(".") :
        with open(each, "r",encoding='utf-8') as i :
            data = json.load(i)
        json_data_list.append(data)
    # print(json_data_list)
    return json_data_list
    
# 得到edges值里的键
def edges_key(json_path):
    json_data_list = standard_json_content(json_path)
    # print(json_data_list)
    edges_values_list = list(json_data_list[0].values())
    edges_dict = edges_values_list[0][0]
    edges_dict_keys_list = list(edges_dict.keys())
    return edges_dict_keys_list

# 将txt里每一行的数据拆成列表
def eachline_data_list(txt_file):
    txt_list = []
    for each_line in txt_file :
        each_line_list = []
        data_num = 0 
        while data_num < 4 :
            each_line_list.append(each_line.split(maxsplit=4)[data_num])
            data_num += 1
        txt_list.append(each_line_list)
    return txt_list

# 将列表里的数据与edges值里的键结合成字典，最后生成列表   
def txt_key_Combine(txt_list,key_list):
    txt_dict_list = []
    for each in txt_list :
        eachline_dict = {}
        dict_num = 0
        while dict_num < 4 :
            eachline_dict.update({key_list[dict_num]:each[dict_num]})
            dict_num += 1
        txt_dict_list.append(eachline_dict)
    return txt_dict_list

# 遍历data/txt路径下的所有txt文件，转化为json格式，并写入到data/json路径下
def Convert_dict(txt_path,json_path,result_path):
    txt_name_list = os.listdir(txt_path)
    keys_list = edges_key(json_path)
    json_data_list = standard_json_content(json_path)
    name_num = 0
    for each in txt_name_list :
        txt_file = open(txt_path+"/%s"%each,"r")
        txt_list = eachline_data_list(txt_file)
        txt_dict_list = txt_key_Combine(txt_list,keys_list)
        json_data_list[0]["edges"] = txt_dict_list
        json_name_list = Obtain_json_name(txt_path)
        with open(result_path+'/%s.json'%json_name_list[name_num], 'w',encoding='utf-8') as f:
            json.dump(json_data_list[0],f,ensure_ascii=False, indent=4)
            print("生成成功")
        name_num += 1




def main():
    os.chdir("./txt")
    txt_path = "D:/hello Python/邓老师任务/test2/data/txt"
    json_path = "D:/hello Python/邓老师任务/test2/data/json"
    result_path = "D:/hello Python/邓老师任务/test2/result"
    Convert_dict(txt_path,json_path,result_path)

if __name__ == '__main__':
    main()
    